package org.ourguy.mymoviesandshows;

import java.util.ArrayList;

import org.ourguy.mymoviesandshows.adapters.EpisodeAdapter;
import org.ourguy.mymoviesandshows.datamodel.Episode;
import org.ourguy.mymoviesandshows.managers.DataAccessException;
import org.ourguy.mymoviesandshows.managers.DataAccessManager;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ScheduleActivity extends ListActivity {

	private DataAccessManager menager;
	private int favouritesAge;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		menager = DataAccessManager.getInstance(this);
		favouritesAge = menager.getFavouritesAge();
		
		refresh();
		
		getListView().setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				startEpisodeInfoActivity(position);
			}
		});
		
		//sliding between tabs
		final TabActivity parrent = (TabActivity)getParent();
		final GestureDetector mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
			
		    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		        int dx = (int) (e2.getX() - e1.getX());
		        // don't accept the fling if it's too short
		        // as it may conflict with a button push
		        if (Math.abs(dx) > 300 && Math.abs(velocityX) > 200) {
		            if (velocityX > 0) {
		            	parrent.getTabHost().setCurrentTab(1);
		            } else {
		            }
		            return true;
		        } else {
		            return false;
		        }
		    }
		});

		View.OnTouchListener gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return mGestureDetector.onTouchEvent(event);
            }
        };
        
        getListView().setOnTouchListener(gestureListener);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(favouritesAge != menager.getFavouritesAge())
			refresh();
	}
	
	
	
	private void refresh()
	{
		new GetUpComingEpisodesAsync(this).execute();
	}
	
	public void startEpisodeInfoActivity(int position) {
    	Intent intent = new Intent(this, EpisodeActivity.class);
    	Episode episode = ((EpisodeAdapter)getListAdapter()).getItem(position);
    	intent.putExtra("show", episode.getSeriesId());
    	intent.putExtra("season", episode.getSeasonNumber());
    	intent.putExtra("episode", episode.getNumber() + 1);
		this.startActivity(intent);
    }
	
	private class GetUpComingEpisodesAsync extends AsyncTask<Void, Void, Boolean> {
    	private ListActivity activity;
    	private ProgressDialog dialog;
    	private Context context;
    	private ArrayList<Episode> episodes = null;
    	
    	public GetUpComingEpisodesAsync(ListActivity activity) {
    		this.activity = activity;
    		this.context = activity;
    		dialog = new ProgressDialog(context);
    	}
    	
    	@Override
    	protected void onPreExecute() {
    		this.dialog.setMessage("Please wait until the list is ready...");
    		this.dialog.setIndeterminate(true);
    		this.dialog.show();
    	}

		@Override
		protected Boolean doInBackground(Void... arg0) {
			try {
				episodes = menager.getUpComing(menager.getFavorites());
	        } catch (DataAccessException e) {
	        	return false;
	        }
			favouritesAge = menager.getFavouritesAge();
	        return true;
		}
		
		@Override
		protected void onPostExecute(final Boolean success) {
			if (dialog.isShowing())
				dialog.hide();
			
			if(success) {
				setListAdapter(new EpisodeAdapter(activity, episodes));
			} else {
				Toast.makeText(context, "Error loading list",
						Toast.LENGTH_LONG).show();
			}
		}
    }
}
